package com.sy.pet.controller;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.sy.pet.commom.ResultBean;
import com.sy.pet.dto.LoginDTO;
import com.sy.pet.entity.User;
import com.sy.pet.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @Author: liangSY
 * @Date: 2024/9/3
 * @ClassName: LoginController
 * @Description: LoginController描述
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    UserService userService;

    @PostMapping
    public ResultBean<SaTokenInfo> login(@RequestBody LoginDTO dto){
        User user = userService.findByAccount(dto.getAccount(), "");
        if(Objects.isNull(user)){
            return ResultBean.failed("账号不存在");
        }
        if(BCrypt.checkpw(user.getPassword(),BCrypt.hashpw(dto.getPassword(), BCrypt.gensalt()))){
            return ResultBean.failed("密码错误");
        }
        StpUtil.login(user.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return ResultBean.success(tokenInfo);
    }

    @GetMapping
    public ResultBean<SaTokenInfo> loginOut(){
        StpUtil.logout();
        return ResultBean.success();
    }
}
